package deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.Random;
import java.util.TreeMap;

/**
 * @author Brook
 */
public class ThreadMXBeanDetection implements Runnable {


    int flag = 1;

    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        ThreadMXBeanDetection mustDeadLock1 = new ThreadMXBeanDetection();
        ThreadMXBeanDetection mustDeadLock2 = new ThreadMXBeanDetection();
        mustDeadLock1.flag = 1;
        mustDeadLock2.flag = 0;
        Thread thread1 = new Thread(mustDeadLock1);
        Thread thread2 = new Thread(mustDeadLock2);
        thread1.start();
        thread2.start();
        Thread.sleep(1000);
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        if(deadlockedThreads != null && deadlockedThreads.length > 0) {
            for (int i = 0; i < deadlockedThreads.length; i++) {
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThreads[i]);
                System.out.println("发现死锁："+ threadInfo.getThreadName());
            }
        }
    }



    @Override
    public void run() {
        System.out.println("flag:="+flag);
        if(flag == 1){
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName()+"获取到o1");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println(Thread.currentThread().getName() + ":转账成功");
                }
            }
        }
        if(flag == 0) {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName()+"获取到o2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println(Thread.currentThread().getName() + ":转账成功");
                }
            }
        }
    }
}
